package com.lexin.action.dao;

import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import com.lexin.action.model.Sequence;
import com.lexin.common.base.TabelName;
import com.lexin.common.utils.JdbcUtils;

@Repository
public class SequenceDaoImpl {
  
  /***
   * 根据表名查询值
   * @param tableName
   * @return
   * @throws Exception
   */
  public long select ( String tableName ) throws Exception {
    QueryRunner query = new QueryRunner(JdbcUtils.getDataSource());
    StringBuffer sql = new StringBuffer("SELECT `value` FROM " + TabelName.Sequence + " WHERE `table_name`='"+tableName+"'");
    Sequence seq = query.query(sql.toString(), new BeanHandler<Sequence>(Sequence.class));
    if (seq==null) return -1;
    return seq.getValue();
  }
  
  /***
   * 根据实体类有赋值的内容作为条件查询所有符合条件的数据
   * @param seq
   * @return
   * @throws Exception
   */
  public List<Sequence> select ( Map<String,String> search, String defNumVal ) throws Exception {
    QueryRunner query = new QueryRunner(JdbcUtils.getDataSource());
    StringBuffer sql = new StringBuffer("SELECT * FROM " + TabelName.Sequence + " WHERE ");
    
    for (String k : search.keySet()) {
    		String v = search.get(k);
			if ( (v==null || v.equals(defNumVal))==false ) {
				sql.append( k+"='"+v+"' " );
			}
	}
    return query.query(sql.toString(), new BeanListHandler<Sequence>(Sequence.class));
  }
  
  /***
   * 更新指定表的序列信息
   * @param seq
   * @return
   * @throws Exception
   */
  public int update ( Sequence seq ) throws Exception {
    QueryRunner query = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "UPDATE " + TabelName.Sequence + " SET `value` = ?, `desc` = ?  WHERE `table_name` = ?";
    return query.update(sql, seq.getValue(), seq.getDesc(), seq.getTable_name());
  }
  
  /***
   * 添加新数据
   * @param seq
   * @return
   * @throws Exception
   */
  public int insert ( Sequence seq ) throws Exception {
    QueryRunner query = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "INSERT INTO " + TabelName.Sequence + " VALUES( ?,?,?)";
    return query.update(sql, seq.getTable_name(), seq.getDesc(), seq.getValue());
  }
  
//  public static void main(String[] args) throws Exception {
//	  SequenceDaoImpl s = new SequenceDaoImpl();
//	  System.out.println(s.select(TabelName.UserAccounts));
//  }
  
}
